package 树;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

public class 深度优先 {

    public static void dfs(TreeNode root){
        if(root == null){
            return;
        }

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode currentNode = stack.pop();

            System.out.println(currentNode.val);

            if(currentNode.left != null){
                stack.push(currentNode.left);
            }

            if(currentNode.right != null){
                stack.push(currentNode.right);
            }
        }
    }

    public static void bfs(TreeNode root){
        if(root == null){
            return;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode currentNode = queue.poll();
            System.out.println(currentNode.val);
            if(currentNode.left != null){
                queue.offer(currentNode.left);
            }
            if(currentNode.right != null){
                queue.offer(currentNode.right);
            }
        }
    }

    public static void recursionDFS(TreeNode root){
        if(root == null){
            return;
        }
        //前序
        System.out.println(root.val);
        if(root.left != null){
            recursionDFS(root.left);
        }
        //中序
        System.out.println(root.val);
        if(root.right != null){
            recursionDFS(root.right);
        }
        //后序
        System.out.println(root.val);
    }
}
